/*
 * Copyright 2016-2019 yoara
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package yhao.infra.web.common.validation;

import com.alibaba.fastjson.JSON;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import yhao.infra.apilist.JsonCommonCodeEnum;
import yhao.infra.apilist.RequestResult;
import yhao.infra.apilist.ValidationForm;
import yhao.infra.common.ContextHolder;
import yhao.infra.web.common.validation.pool.ValidationPoolBean;

import java.util.HashMap;
import java.util.Map;

/**
 * forom验证处理切面
 *
 * <p>标记注解{@link RequestMapping}，{@link GetMapping}，{@link PostMapping}，
 * 参数中包含{@link ValidationForm}的form实现类将会被验证
 *
 * @author yoara
 */
@Aspect
@Component
public class ValidationAop {
    @Autowired
    protected ValidationPoolBean validationPoolBean;

    private final String mircoServiceReturnType = RequestResult.class.getSimpleName();

    @Around(value = "@annotation(rm)")
    public Object validate(ProceedingJoinPoint joinPoint, RequestMapping rm) throws Throwable {
        return doValidate(joinPoint);
    }

    @Around(value = "@annotation(gm)")
    public Object validateGet(ProceedingJoinPoint joinPoint, GetMapping gm) throws Throwable {
        return doValidate(joinPoint);
    }

    @Around(value = "@annotation(pm)")
    public Object validatePost(ProceedingJoinPoint joinPoint, PostMapping pm) throws Throwable {
        return doValidate(joinPoint);
    }

    private Object doValidate(ProceedingJoinPoint joinPoint) throws Throwable {
        if((boolean) ContextHolder.getContextData(HasSpringValidationContextKey.class)){
            return joinPoint.proceed();
        }
        Object[] args = joinPoint.getArgs();
        if(args==null||args.length==0){
            return joinPoint.proceed();
        }
        for(Object arg:args){
            if(arg instanceof ValidationForm){
                ValidationResult result = validationPoolBean.validationParam((ValidationForm)arg);
                if(result.hasError()){
                    if(joinPoint.getSignature().toLongString().contains(mircoServiceReturnType)){
                        RequestResult requestResult =
                                new RequestResult(false,null,result.getErrorMessages().get(0).getMessage());
                        return requestResult;
                    }else{
                        Map<String, Object> jsonResult = new HashMap<>();
                        jsonResult.put("status", JsonCommonCodeEnum.E0002.getStatus());
                        jsonResult.put("message", result.getErrorMessages().get(0).getMessage());
                        jsonResult.put("result", null);
                        return JSON.toJSONString(jsonResult);
                    }
                }
            }
        }
        return joinPoint.proceed();
    }
}
